package com.wolf.cx330.view.view

import android.content.Context
import android.graphics.Camera
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.wolf.cx330.base.dp
import com.wolf.cx330.base.getAvatar

/**
 * Camera 翻转动画
 */
class CameraAnimView(context: Context, attributeSet: AttributeSet) : View(context, attributeSet) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val imageWidth = 200.dp()
    private val bitmap = resources.getAvatar(imageWidth.toInt())
    private val camera = Camera().apply {

    }
    private var canvasRotate: Float = 0F
        set(value) {
            field = value
            invalidate()
        }
    private var cameraRotateX: Float = 0F
        set(value) {
            field = value
            invalidate()
        }

    private val top = -imageWidth
    private val bottom = imageWidth

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        camera.rotateX(cameraRotateX)
        //  上面
        canvas.save()
        canvas.translate(width / 2F, height / 2F)
        canvas.rotate(-canvasRotate)
        //  4. 切完之后 恢复操作↑↑↑
        canvas.clipRect(
            -imageWidth,
            -imageWidth,
            imageWidth,
            0F
        )
        //  3. 旋转之后 切一块下来[中间往下]↑↑↑
        canvas.rotate(canvasRotate)
        //  2. 移动之后 将其旋转↑↑↑
        canvas.translate(-width / 2F, -height / 2F)
        //  1. 将Canvas 移动到原点位置↑↑↑
        canvas.drawBitmap(bitmap, width / 2 - imageWidth / 2, height / 2 - imageWidth / 2, paint)
        canvas.restore()

        //  下面
        canvas.save()

        canvas.translate(width / 2F, height / 2F)
        canvas.rotate(-canvasRotate)
        //  5. 投影之后 恢复操作
        camera.applyToCanvas(canvas)
        //  4. 切完之后 将其Camera旋转应用↑↑↑
        canvas.clipRect(
            -imageWidth,
            0F,
            imageWidth,
            imageWidth
        )
        //  3. 旋转之后 切一块下来[中间往下]↑↑↑
        canvas.rotate(canvasRotate)
        //  2. 移动之后 将其旋转↑↑↑
        canvas.translate(-width / 2F, -height / 2F)
        //  1. 将Canvas 移动到原点位置↑↑↑
        canvas.drawBitmap(bitmap, width / 2 - imageWidth / 2, height / 2 - imageWidth / 2, paint)
        canvas.restore()
    }

}